
import { ref } from "vue";
import { useStore } from '@/stores/data'
import { dialog } from '@/utils/dialog'
type Json = Record<string, any>;
type WSStatus = "idle" | "connecting" | "open" | "closed" | "blocked";
const store = useStore()
const WS_URL = `ws://192.168.1.153:8000/ws/chat`;
const HEARTBEAT_MS = 25_000;
const MAX_BACKOFF_MS = 30_000;

let ws: WebSocket | null = null;
let heartbeatTimer: number | null = null;
let reconnectTimer: number | null = null;
let backoff = 1000;
let everOpened = false;               // ✅ 只要成功连通过一次才允许自动重连

const wsStatus = ref<WSStatus>("idle");
const lastMsg = ref<Json | null>(null);
const lastError = ref<string>("");

// 清洗 raw token，防止 "null"/"undefined" 等脏值
function sanitizeRawToken(raw: any): string {
  const s = String(raw ?? "").trim();
  if (!s || s === "null" || s === "undefined" || s === "None") return "";
  // 允许存裸 JWT 或已带 Bearer 的字符串
  return s.toLowerCase().startsWith("bearer ") ? s.slice(7).trim() : s;
}

function getToken(): string {
  const raw = localStorage.getItem("token"); // 建议存“裸JWT”
  const jwt = sanitizeRawToken(raw);
  return jwt ? `Bearer ${jwt}` : "";         // 统一带 Bearer
}

function makeWsUrl() {
  const t = getToken();
  return t ? `${WS_URL}?token=${encodeURIComponent(t)}` : WS_URL;
}

function sendJson(obj: Json) {
  if (!ws || ws.readyState !== WebSocket.OPEN) return false;
  ws.send(JSON.stringify(obj));
  return true;
}

function startHeartbeat() {
  stopHeartbeat();
  heartbeatTimer = window.setInterval(() => sendJson({ type: "ping" }), HEARTBEAT_MS);
}
function stopHeartbeat() {
  if (heartbeatTimer) { clearInterval(heartbeatTimer); heartbeatTimer = null; }
}

function scheduleReconnect() {
  // ✅ 没有成功连通过，或者当前没有有效 token —— 不重连
  if (!everOpened) return;
  if (!getToken()) { wsStatus.value = "blocked"; return; }
  if (reconnectTimer) return;

  const delay = Math.min(backoff, MAX_BACKOFF_MS);
  reconnectTimer = window.setTimeout(() => {
    reconnectTimer = null;
    connect();
    backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);
  }, delay);
}

function connect() {
  const token = getToken();
  if (!token) {
    wsStatus.value = "blocked";
    lastError.value = "缺少/无效令牌，无法建立 WS 连接";
    return;
  }
  if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) return;

  try {
    wsStatus.value = "connecting";
    lastError.value = "";
    const url = makeWsUrl();
    // console.log("WS connect ->", url); // 调试用
    ws = new WebSocket(url);

    ws.onopen = () => {
      wsStatus.value = "open";
      everOpened = true;            // ✅ 标记：从这一刻起才允许自动重连
      backoff = 1000;
      startHeartbeat();
    };

    ws.onmessage = (ev) => {
      const res = JSON.parse(ev.data);
      if (res.code === 0) {
        // 成功：msg.type / msg.data
        switch (res.type) {
          case "danmu_event":
            switch (res.data.type) {
              case "stats":
                if(res.data.current) store.liveData.current = res.data.current
                if(res.data.total) store.liveData.total = res.data.total
                break;
            }
            store.liveData.danmu.push(res.data)
            break;
          case "gu":
            store.userInfo = res.data
            break;
          case "gc":
            store.userConfig = res.data
            break;
          case "uc":
            store.userConfig = res.data
            // alert("修改成功")
            dialog.alert({ iconType: 'sc', message: '修改成功'});
            break;
          default:
            break;
        }
      } else {
        // 失败：msg.type / msg.code / msg.msg
      }
    };

    ws.onerror = () => { };

    ws.onclose = (ev) => {
      stopHeartbeat();
      wsStatus.value = "closed";

      // 如果后端改成“accept 后 close(4401)”，这里能拿到 4401，从而不重连
      if (ev.code === 4401 || ev.code === 4001 || ev.code === 1008) {
        lastError.value = `鉴权失败（code=${ev.code}）`;
        wsStatus.value = "blocked";
        return;
      }

      scheduleReconnect(); // 只有 everOpened==true 才会进来
    };
  } catch (e: any) {
    wsStatus.value = "closed";
    lastError.value = e?.message || String(e);
  }
}

function disconnect() {
  stopHeartbeat();
  if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
  if (ws) { try { ws.close(); } catch { } }
  ws = null;
  wsStatus.value = "closed";
}

// —— 业务方法（默认不带 room，后端按 uid 私有房间） ——
function sendDanmu(id: string, extra: Json = {}) { return sendJson({ type: "danmu", data: { id, ...extra } }); }
function sendRoomMessage(data: Json) { return sendJson({ type: "room_message", data }); }
function sendBroadcast(data: Json) { return sendJson({ type: "broadcast", data }); }

const sendGetUserInfo = () => sendJson({ type: "gu", data: null });
const sendGetUserConfig = () => sendJson({ type: "gc", data: null });
const sendSetUserConfig = (data: unknown) => sendJson({ type: "uc", data });
export function useChatWS() {
  return {
    wsStatus, lastMsg, lastError,
    connect, disconnect,
    sendDanmu, sendRoomMessage, sendBroadcast, sendGetUserInfo, sendGetUserConfig, sendSetUserConfig
  };
}
